package com.sharefang.aproject;

import android.app.Application;
import android.content.Context;
import android.content.Intent;

import com.sharefang.aproject.activity.LoginActivity;
import com.sharefang.aproject.bean.UserBean;
import com.sharefang.aproject.presenter.UserResultPresenter;
import com.sharefang.aproject.utils.CacheHelper;
import com.sharefang.aproject.utils.CheckUtil;
import com.sharefang.aproject.utils.CrashHandler;
import com.sharefang.aproject.view.IUserInfoView;
import com.squareup.leakcanary.LeakCanary;

import static com.sharefang.aproject.constant.CacheKey.USER_BEAN;

/**
 * Created by Administrator on 2016/8/10.
 */

public class BaseApplication extends Application implements IUserInfoView {
    private static BaseApplication mApplication;
    private Context mApplicationContext;
    UserBean userBean;
    UserResultPresenter resultPresenter = new UserResultPresenter(this, this);

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        mApplicationContext = this;

        //Crash抓取
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);

        //抓取内存泄漏信息
        LeakCanary.install(this);

        initUserInfo();

    }

    private void initUserInfo() {
        if (this.userBean != null)
            return;
        if (CheckUtil.isLogined()) {
            this.userBean = (UserBean) CacheHelper.getAsObject(USER_BEAN);
            if (userBean == null) {
                resultPresenter.getUserInfo(-1);
            }
        }
    }

    public UserBean getUserBean() {
        return userBean;
    }

    public void setUserBean(UserBean userBean) {
        this.userBean = userBean;
    }

    private void transferActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    public static BaseApplication getInstance() {
        return mApplication;
    }

    public Context getApplicationContext() {
        return mApplicationContext;
    }

    @Override
    public void doUserInfo(UserBean userBean) {
        if (userBean == null) {
            transferActivity();
        } else {
            CacheHelper.put(USER_BEAN, userBean);
        }
    }

    @Override
    public void showFailedError(String message) {

    }
}
